Primary exercises

  1. A function with if/else statements.

Let’s take the following from a World Health Organization document:

The categories can be enumerated as follows:

group condition for age [y]
adult age > 19
adolescent age >= 10 && age <= 19
child age >= 1 && age < 10
infant age < 1

Implement a function ageGroup which takes age argument (in years) and returns the age group label.

Function template Here is a template of the ageGroup function:

ageGroup <- function( age ) { 
  # age: age given in years
  ...
}

and here are expected results:

ageGroup(0)   # "infant"
ageGroup(10)  # "adolescent"
ageGroup(9)   # "child"
ageGroup(20)  # "adult"
ageGroup(-1)  # should generate an error

To generate the error we request the program to ?stop with an error message.

# 1) Poor implementation
#
ageGroup <- function( age ) { 
  # age: age given in years
  result <- "child"
  if( age > 19 ) {
    result <- "adult"
  }
  if( age >= 10 & age <= 19 ) {
    result <- "adolescent"
  } 
  if( age < 1 ) {
    result <- "infant"
  } 
  if( age < 0 ) {
    stop( "Age can't be negative." )
  } 
  result
}
# 2) Improved implementation 
# 
# In the previous scenario: when `age` is 30 and the `result` is set to `adult` 
# it makes no sense to check whether `age` is in other ranges,  
# `if`/`else` construction allows for that.
#
ageGroup <- function( age ) { 
  # age: age given in years
  if( age > 19 ) {
    result <- "adult"
  } else if( age >= 10 ) {
    result <- "adolescent"
  } else if( age >= 1 ) {
    result <- "child"
  } else if( age >= 0 ) {
    result <- "infant"
  } else {
    stop( "Age can't be negative." )
  }
  result
}
ageGroup(0)   # "infant"
[1] "infant"
ageGroup(10)  # "adolescent"
[1] "adolescent"
ageGroup(9)   # "child"
[1] "child"
ageGroup(20)  # "adult"
[1] "adult"
ageGroup(-1)  # should generate an error
Error in ageGroup(-1): Age can't be negative.


Copyright © 2022 Biomedical Data Sciences (BDS) | LUMC